package com.dubbo.test.filter;

import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RateLimiterRegistry;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.time.Duration;


/**
 * @Auther: liuyj
 * @Date: 2021/09/07/11:06
 * @Description:
 */
@Activate(group = CommonConstants.PROVIDER, order = -111000)
public class MyFilter implements Filter {

    // 创建限流器配置
    RateLimiterConfig config =  RateLimiterConfig.custom()
            .limitRefreshPeriod(Duration.ofMillis(1000))
            .limitForPeriod(1)
            .timeoutDuration(Duration.ofMillis(1000))
            .build();
    // 创建限流器注册器RateLimiterRegistry
    RateLimiterRegistry rateLimiterRegistry = RateLimiterRegistry.of(config);

    // 通过RateLimiter创建限流器
    RateLimiter rateLimiter = RateLimiter.of("my-rateLimiter", config);


    @Override
    public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException {
//        System.out.println(new Date()+"==========================myfilter===================");
       /* Supplier<Result> decorateSupplier = RateLimiter
                .decorateSupplier(rateLimiter, () -> invoker.invoke(inv));
        Result result = Try.ofSupplier(decorateSupplier)
                .get();*/
        return rateLimiter.executeSupplier(() -> invoker.invoke(inv));
    }

}